package bfh._4_semester.simpleCMS.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.*;

public class LoginScreen implements EntryPoint, ClickHandler  { //ClickListener {
	private DBConnectionAsync rpc;
	private TextBox usernameBox;
	private TextBox passwordBox;
	private Button OK;
	
	private Grid g;

	public LoginScreen() {
		rpc = (DBConnectionAsync) GWT.create(DBConnection.class);
		ServiceDefTarget target = (ServiceDefTarget) rpc;
		// The path 'MySQLConnection' is determined in
		// ./public/LoginScreen.gwt.xml
		// This path directs Tomcat to listen for this context on the server
		// side,
		// thus intercepting the rpc requests.
		String moduleRelativeURL = GWT.getModuleBaseURL() + "MySQLConnection";
		target.setServiceEntryPoint(moduleRelativeURL);
		initGUI();
	}

	public void onModuleLoad() {
//		RootPanel.get().add(this);
		RootPanel.get().add(g);
	}

	// }
	private void initGUI() {
		g = new Grid(3, 2);
		usernameBox = new TextBox();
		passwordBox = new TextBox();
		OK = new Button("OK");
		g.setWidget(0, 0, new Label("Username: "));
		g.setWidget(0, 1, usernameBox);
		g.setWidget(1, 0, new Label("Password: "));
		g.setWidget(1, 1, passwordBox);
		g.setWidget(2, 1, OK);
		
		OK.addClickHandler(this);
		
		
	}

	private class AuthenticationHandler<T> implements AsyncCallback<User> {
		public void onFailure(Throwable ex) {
		RootPanel.get().add(new HTML("RPC call failed."));
		
		System.out.println("login failed");
		
		}

		public void onSuccess(User result) {
			// do stuff on success with GUI, like load the next GUI element
			
			System.out.println("login succeded");
		}
	}
	@Override
	public void onClick(ClickEvent event) {

//		usernameBox.setText("User name was set by clicking the buttion OK");
		
		if (event.equals(OK)) {
			AsyncCallback<User> callback = new AuthenticationHandler<User>();
			rpc.authenticateUser(usernameBox.getText(), passwordBox.getText(),
					callback);
		}
		
	}
}